package com.jackrain.nea.fc.vp.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.jackrain.nea.config.Resources;
import com.jackrain.nea.core.db.Tools;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.fc.cp.api.ChrusersWebQueryCmd;
import com.jackrain.nea.fc.utils.Constants;
import com.jackrain.nea.fc.vp.api.CvipSearchCmd;
import com.jackrain.nea.fc.vp.api.ViewCvipAddrSaveCmd;
import com.jackrain.nea.fc.vp.mapper.ViewCvipAddrMapper;
import com.jackrain.nea.sys.CommandAdapter;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.util.ValueHolder;
import com.jackrain.nea.web.QueryCmd;
import com.jackrain.nea.web.face.User;
import com.jackrain.nea.web.query.DefaultWebEvent;
import com.jackrain.nea.web.query.QuerySession;
import com.jackrain.nea.web.query.QuerySessionImpl;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.HashMap;

/**
 * FC-会员接口-VIP收货地址-F4新增/修改 —> FC
 *
 * @author WSL
 * @create 2017/11/13
 */
@Slf4j
@Component
@Service(protocol = "dubbo", validation = "true", version = "1.0", group = "vp")
public class ViewCvipAddrSaveCmdImpl extends CommandAdapter implements ViewCvipAddrSaveCmd {

    @Reference(version = "2", group = "cp")
    private QueryCmd queryCmd;

    @Reference(version = "1.0", group = "cp")
    private ChrusersWebQueryCmd chrusersWebQueryCmd;

    @Reference(version = "1.0", group = "vp")
    private CvipSearchCmd cvipSearchCmd;

    @Override
    @Transactional
    public ValueHolder execute(HashMap map) throws NDSException {
        // 常量
        String provinceStr = "CP_C_PRO_ID";
        String cityStr = "CP_C_CITY_ID";
        String countyStr = "CP_C_DIST_ID";
        String isDefault = "ISDEFAULT";
        String vipName = "RECEIVER";
        String vipMobile = "MOBIL";
        String vipAddress = "ADDRESS";

        ValueHolder vh = new ValueHolder();
        JSONObject param = JSON.parseObject(JSON.toJSONStringWithDateFormat(map.get("param"), "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteMapNullValue), Feature.OrderedField);
        log.info("ViewCvipAddrSaveCmdImpl--param-->{}",param);

        // Mapper
        ViewCvipAddrMapper viewCvipAddrMapper = ApplicationContextHandle.getBean(ViewCvipAddrMapper.class);
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());

        // 获取data插入参数集合
        JSONArray dataArray = param.getJSONArray("data");
        if (dataArray.size() > 100) {
            throw new NDSException("数据量过大！");
        }
        // 获取user模拟querySession
        User user = chrusersWebQueryCmd.getUser("INTER99999");

        for (int i = 0; i < dataArray.size(); i++) {
            JSONObject paramJson = dataArray.getJSONObject(i);
            // 字段翻译
            JSONObject fcParam = new JSONObject();
            // VIP类型
            String cVipTypeGroupId = paramJson.getString("VP_C_VIPTYPEGROUP_ID");
            if (null == cVipTypeGroupId || "".equals(cVipTypeGroupId)) {
                throw new NDSException("VP_C_VIPTYPEGROUP_ID, 不能为空");
            }
            Long cVipTypeGroupIdFc = viewCvipAddrMapper.getCvipTypeGroupId(cVipTypeGroupId);
            // VIP_ID
            String cardId = paramJson.getString("VP_C_VIP_ID");
            if (null == cardId || "".equals(cardId)) {
                throw new NDSException("VP_C_VIP_ID, 不能为空");
            }

            JSONObject paramOpen = new JSONObject();
            JSONObject fixedColumns = new JSONObject();
            fixedColumns.put("ACC.ECODES", cardId);
            fixedColumns.put("ACC.VP_C_VIPTYPEGROUP_ID", cVipTypeGroupIdFc);
            JSONArray searchType = new JSONArray();
            JSONObject searchItem = new JSONObject();
            searchItem.put("name", "ACC.ECODES");
            searchItem.put("type", "exact");
            searchType.add(searchItem);
            searchItem = new JSONObject();
            searchItem.put("name", "ACC.VP_C_VIPTYPEGROUP_ID");
            searchItem.put("type", "exact");
            searchType.add(searchItem);
            paramOpen.put("fixedcolumns", fixedColumns);
            paramOpen.put("searchtype", searchType);

            QuerySession querySession = new QuerySessionImpl(user);
            DefaultWebEvent event = new DefaultWebEvent("vipAddr", new HashMap(16));
            event.put("param", paramOpen);
            querySession.setEvent(event);
            Object ids = cvipSearchCmd.execute(querySession).get("IDS");
            if (null == ids) {
                throw new NDSException("IDS为空！");
            }
            JSONArray idsArray = JSON.parseArray(ids.toString());
            if (idsArray.size() > 1) {
                throw new NDSException("IDS长度大于1！" + idsArray.size());
            } else if (idsArray.size() == 0) {
                throw new NDSException("IDS为空！");
            }
            Long cVipId = idsArray.getLong(0);
            if (null == cVipId) {
                throw new NDSException("VP_C_VIP_ID,传值错误,无法找到对应ID");
            }
            fcParam.put("VP_C_VIP_ID", cVipId);
            // 序号
            Long lineFc = paramJson.getLong("LINE");
            if (null == lineFc) {
                throw new NDSException("LINE,不能为空");
            }
            fcParam.put("LINE", lineFc);
            // 收货人
            if (paramJson.containsKey(vipName)) {
                fcParam.put("RECEIVER", paramJson.getString("RECEIVER"));
            }
            // 联系电话
            if (paramJson.containsKey(vipMobile)) {
                fcParam.put("MOBIL", paramJson.getString("MOBIL"));
            }
            // 省份
            Object cProId = null;
            if (paramJson.containsKey(provinceStr)) {
                String province = paramJson.getString("CP_C_PRO_ID");

                HashMap hashMapOther = new HashMap(16);
                hashMapOther.put("tableName", "CP_C_REGION");
                hashMapOther.put("fields", "ID");
                JSONObject whereJson = new JSONObject();
                whereJson.put("REGIONTYPE", "PROV");
                whereJson.put("ENAME", province);
                hashMapOther.put("whereKeys", whereJson);
                hashMapOther.put("type", HashMap.class);
                HashMap dataMap = (HashMap) queryCmd.queryTable(hashMapOther);
                if (null == dataMap || dataMap.size() == 0) {
                    throw new NDSException("根据省ENAME未查询到数据！");
                }
                cProId = dataMap.get("ID");

                if (null == cProId) {
                    throw new NDSException("CP_C_PRO_ID,传值错误,无法找到对应ID");
                }
                fcParam.put("CP_C_PRO_ID", cProId);
            }
            // 城市
            Object cCityId = null;
            if (paramJson.containsKey(cityStr)) {
                String city = paramJson.getString("CP_C_CITY_ID");

                HashMap hashMapOther = new HashMap(16);
                hashMapOther.put("tableName", "CP_C_REGION");
                hashMapOther.put("fields", "ID");
                JSONObject whereJson = new JSONObject();
                whereJson.put("REGIONTYPE", "CITY");
                whereJson.put("ENAME", city);
                whereJson.put("C_UP_ID", cProId);
                hashMapOther.put("whereKeys", whereJson);
                hashMapOther.put("type", HashMap.class);
                HashMap dataMap = (HashMap) queryCmd.queryTable(hashMapOther);
                if (null == dataMap || dataMap.size() == 0) {
                    throw new NDSException("根据市ENAME未查询到数据！");
                }
                cCityId = dataMap.get("ID");

                if (null == cCityId) {
                    throw new NDSException("CP_C_CITY_ID,传值错误,无法找到对应ID");
                }
                fcParam.put("CP_C_CITY_ID", cCityId);
            }
            // 区县
            if (paramJson.containsKey(countyStr)) {
                String county = paramJson.getString("CP_C_DIST_ID");

                HashMap hashMapOther = new HashMap(16);
                hashMapOther.put("tableName", "CP_C_REGION");
                hashMapOther.put("fields", "ID");
                JSONObject whereJson = new JSONObject();
                whereJson.put("REGIONTYPE", "DIST");
                whereJson.put("ENAME", county);
                whereJson.put("C_UP_ID", cCityId);
                hashMapOther.put("whereKeys", whereJson);
                hashMapOther.put("type", HashMap.class);
                HashMap dataMap = (HashMap) queryCmd.queryTable(hashMapOther);
                if (null == dataMap || dataMap.size() == 0) {
                    throw new NDSException("根据区ENAME未查询到数据！");
                }
                Object cCountyId = dataMap.get("ID");

                if (null == cCountyId) {
                    throw new NDSException("CP_C_DIST_ID,传值错误,无法找到对应ID");
                }
                fcParam.put("CP_C_DIST_ID", cCountyId);
            }
            // 收货地址
            if (paramJson.containsKey(vipAddress)) {
                fcParam.put("ADDRESS", paramJson.getString("ADDRESS"));
            }
            // 是否默认
            if (0 == paramJson.getInteger(isDefault)) {
                fcParam.put("ISDEFAULT", 'N');
            } else if (1 == paramJson.getInteger(isDefault)) {
                fcParam.put("ISDEFAULT", 'Y');
            }

            // 通过VIPID和序号查询唯一数据是否有值用来判断 新增 或 修改
            int count = viewCvipAddrMapper.check(cVipId, lineFc);
            if (count > 0) {
                // 修改
                vh = modify(fcParam, viewCvipAddrMapper, timestamp, queryCmd);
            } else {
                // 新增
                vh = add(fcParam, viewCvipAddrMapper, timestamp, queryCmd);
            }
        }

        vh.put("status", 0);
        return vh;
    }

    /**
     * 新增
     *
     * @param fcParam
     * @param viewCvipAddrMapper
     * @param timestamp
     */
    private ValueHolder add(JSONObject fcParam, ViewCvipAddrMapper viewCvipAddrMapper, Timestamp timestamp, QueryCmd queryCmd) {
        ValueHolder vh = new ValueHolder();
        log.debug("ViewCvipAddrSaveCmdImpl-->add");

//        log.info("VIP收货地址=======>新增");
        // userId
        HashMap hashMapOther = new HashMap(16);
        hashMapOther.put("tableName", "USERS");
        hashMapOther.put("fields", "ID,NAME,ENAME");
        JSONObject whereJson = new JSONObject();
        whereJson.put("NAME", "INTER99999");
        hashMapOther.put("whereKeys", whereJson);
        hashMapOther.put("type", HashMap.class);
        HashMap dataMap = (HashMap) queryCmd.queryTable(hashMapOther);
        if (null == dataMap || dataMap.size() == 0) {
            throw new NDSException("根据NAME未查询到数据！");
        }

        // ID
        fcParam.put("ID", Tools.getSequence("VP_C_VIP_ADDR"));
        // AD_CLIENT_ID
        fcParam.put("AD_CLIENT_ID", "37");
        // AD_ORG_ID
        fcParam.put("AD_ORG_ID", "27");
        // 创建人
        fcParam.put("OWNERID", dataMap.get("ID"));
        fcParam.put("OWNERNAME", dataMap.get("NAME"));
        fcParam.put("OWNERENAME", dataMap.get("ENAME"));
        // 创建时间
        fcParam.put("CREATIONDATE", timestamp);
        // 修改人
        fcParam.put("MODIFIERID", dataMap.get("ID"));
        fcParam.put("MODIFIERNAME", dataMap.get("NAME"));
        fcParam.put("MODIFIERENAME", dataMap.get("ENAME"));
        // 修改时间
        fcParam.put("MODIFIEDDATE", timestamp);
        log.debug("ViewCvipAddrSaveCmdImpl--fcParam_add-->{}",fcParam.toJSONString());

//        log.info("fcParam:" + fcParam.toJSONString());

        // 执行新增
        int count = viewCvipAddrMapper.insert(fcParam);
        if (count < 0) {
            throw new NDSException("新增失败");
        }
        vh.put("message", Resources.getMessage("新增成功"));
        return vh;
    }

    /**
     * 修改
     *
     * @param fcParam
     * @param viewCvipAddrMapper
     * @param timestamp
     */
    private ValueHolder modify(JSONObject fcParam, ViewCvipAddrMapper viewCvipAddrMapper, Timestamp timestamp, QueryCmd queryCmd) {
//        log.info("VIP收货地址=======>修改");
        log.debug("ViewCvipAddrSaveCmdImpl-->modify");

        ValueHolder vh = new ValueHolder();
        HashMap hashMapOther = new HashMap(16);
        hashMapOther.put("tableName", "USERS");
        hashMapOther.put("fields", "ID,NAME,ENAME");
        JSONObject whereJson = new JSONObject();
        whereJson.put("NAME", "INTER99999");
        hashMapOther.put("whereKeys", whereJson);
        hashMapOther.put("type", HashMap.class);
        HashMap dataMap = (HashMap) queryCmd.queryTable(hashMapOther);
        if (null == dataMap || dataMap.size() == 0) {
            throw new NDSException("根据NAME未查询到数据！");
        }

        // 修改人
        fcParam.put("MODIFIERID", dataMap.get("ID"));
        fcParam.put("MODIFIERNAME", dataMap.get("NAME"));
        fcParam.put("MODIFIERENAME", dataMap.get("ENAME"));

        // 修改时间
        fcParam.put("MODIFIEDDATE", timestamp);

//        log.info("fcParam:" + fcParam.toJSONString());
        log.debug("ViewCvipAddrSaveCmdImpl--fcParam_modify-->{}",fcParam);

        // 执行修改
        int count = viewCvipAddrMapper.update(fcParam);
        if (count < 0) {
            throw new NDSException("修改失败");
        }
        vh.put("message", Resources.getMessage("修改成功"));
        return vh;
    }

}
